package cn.kow.kmall.controller;

import cn.kow.kmall.common.constant.RedisKeyConstants;
import cn.kow.kmall.common.enums.ItemStatusEnum;
import cn.kow.kmall.common.util.ItemUtils;
import cn.kow.kmall.core.constant.KmallStatusConstant;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.core.util.JsonUtils;
import cn.kow.kmall.core.util.MoneyUtils;
import cn.kow.kmall.pojo.dto.ItemListDTO;
import cn.kow.kmall.pojo.dto.ItemQueryDTO;
import cn.kow.kmall.pojo.dto.ItemSpecDTO;
import cn.kow.kmall.pojo.entity.Item;
import cn.kow.kmall.pojo.entity.ItemAttribute;
import cn.kow.kmall.pojo.entity.ItemCategory;
import cn.kow.kmall.pojo.entity.Sku;
import cn.kow.kmall.pojo.vo.ItemAttributeVO;
import cn.kow.kmall.pojo.vo.ItemBaseInfoVO;
import cn.kow.kmall.pojo.vo.ItemVO;
import cn.kow.kmall.pojo.vo.SkuVO;
import cn.kow.kmall.service.ItemCategoryService;
import cn.kow.kmall.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-05-13 15:27
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/item")
public class ItemController {

    /**
     * 商品服务
     */
    @Autowired
    private ItemService itemService;

    /**
     * 分类服务
     */
    @Autowired
    private ItemCategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分类商品列表
     * @param categoryL1Id
     * @param categoryL2Id
     * @return
     */
    @GetMapping(value = "/list/l2Items2")
    public KmallResult itemList(@RequestParam Long categoryL1Id, @RequestParam Long categoryL2Id) {
        Map<String, Object> result = new HashMap<>();

        ItemCategory category = categoryService.getById(categoryL1Id);

        List<ItemCategory> subCategoryList = categoryService.listByParentId(categoryL1Id);
        List<Map<String,Object>> categoryL2List = new ArrayList<>();
        for (ItemCategory subCategory : subCategoryList) {
            Map<String,Object> categoryL2 = new HashMap<>();
            categoryL2.put("id", subCategory.getId());
            categoryL2.put("name", subCategory.getName());
            categoryL2List.add(categoryL2);
        }
        Map<String,Object> categoryL2 = new HashMap<>();
        categoryL2.put("id", 0);
        categoryL2.put("title", "全部");
        categoryL2List.add(0, categoryL2);

        // 组装VO
        ItemQueryDTO queryDTO = new ItemQueryDTO();
        queryDTO.setCategoryId(categoryL2Id);
        queryDTO.setItemStatus(ItemStatusEnum.ONLINE.getValue());
        queryDTO.setPage(0);
        queryDTO.setSize(20);
        List<ItemListDTO> itemList = itemService.queryItemList(queryDTO);

        result.put("name", category.getName());
        result.put("hasMore", false);
        result.put("itemList", itemList);
        result.put("categoryL2List",categoryL2List);
        return KmallResult.success(result);
    }

    /**
     * 获取商品详情
     * @param itemId
     * @return
     */
    @GetMapping(value = "/detail")
    public KmallResult itemInfo(@RequestParam Long itemId) {
        // 获取Item
        Item item = itemService.getItemById(itemId);
        List<Sku> skuList = itemService.listSkuByItemId(itemId);
        List<ItemAttribute> itemAttributeList = itemService.listItemAttribute(itemId);

        // ItemVO
        ItemBaseInfoVO baseInfo = new ItemBaseInfoVO();
        baseInfo.setItemId(item.getId());
        baseInfo.setItemName(item.getName());
        baseInfo.setCategoryId(item.getCategoryId());
        baseInfo.setSimpleDesc(item.getSimpleDesc());
        baseInfo.setPrimaryPic(item.getPrimaryPic());
        baseInfo.setDetailHtml(item.getDetail());
        baseInfo.setSwiperPics(Arrays.asList(item.getSwiperPic().split(",")));
        baseInfo.setStatus(1);

        // SpecVO
        // 商品规格
        String itemSpec = item.getItemSpec();
        List<ItemSpecDTO> specList = JsonUtils.toList(itemSpec, ItemSpecDTO.class);

        Integer sellingPrice = Integer.MAX_VALUE;
        Integer stockNum = 0;
        // SKUVO
        Map<String, SkuVO> skuMap = new HashMap<>(skuList.size());
        for (Sku sku : skuList) {
            Long skuId = sku.getId();
            SkuVO skuVO = SkuVO.builder().skuId(skuId).skuName(sku.getItemName()).stockNum(sku.getStockNum())
                    .sellingPrice(MoneyUtils.Fen2YuanStr(sku.getSellingPrice()))
                    .valid(sku.getStockNum() > 0).skuSpecId(sku.getSkuSpecId()).skuSpecName(ItemUtils.formatSkuSpecName(sku.getSkuSpecName()))
                    .build();
            skuMap.put(sku.getSkuSpecId(), skuVO);
            sellingPrice = Math.min(sellingPrice, sku.getSellingPrice());
            stockNum += sku.getStockNum();
        }

        // attribute
        List<ItemAttributeVO> attrList = itemAttributeList.stream().map(itemAttribute
                -> new ItemAttributeVO(itemAttribute.getName(), itemAttribute.getValue())).collect(Collectors.toList());

        baseInfo.setSoldOut(stockNum > 0);
        baseInfo.setSellingPrice(MoneyUtils.Fen2YuanStr(sellingPrice));

        ItemVO itemVO = new ItemVO();
        itemVO.setBaseInfo(baseInfo);
        itemVO.setSkuMap(skuMap);
        itemVO.setAttrList(attrList);
        itemVO.setSpecList(specList);
        return KmallResult.success(itemVO);
    }

    /**
     * 获取商品详情
     * @param skuId
     * @return
     */
    @GetMapping(value = "/sku/{skuId}")
    public KmallResult skuInfo(@PathVariable Long skuId) {
        // 获取Item
        Sku sku = itemService.getSkuById(skuId);
        SkuVO skuVO = new SkuVO();
        skuVO.setSkuId(sku.getId());
        skuVO.setItemId(sku.getItemId());
        skuVO.setSellingPrice(MoneyUtils.Fen2YuanStr(sku.getSellingPrice()));
        skuVO.setStockNum(sku.getStockNum());
        skuVO.setSkuSpecName(sku.getSkuSpecName());
        return KmallResult.success(skuVO);
    }

    /**
     * 推荐商品
     * @return
     */
    @GetMapping(value = "/related")
    public KmallResult relatedItemList() {
        return KmallResult.success();
    }

    /**
     * 分类商品列表
     * @param wd
     * @return
     */
    @GetMapping(value = "/search")
    public KmallResult itemSearch(@RequestParam String wd, @RequestParam Integer page, @RequestParam Integer size) {
        Map<String, Object> result = new HashMap<>();
        List<ItemListDTO> itemList = new ArrayList<>();
        if (!StringUtils.isBlank(wd)) {
            ItemQueryDTO queryDTO = ItemQueryDTO.builder().itemName(wd)
                    .itemStatus(ItemStatusEnum.ONLINE.getValue())
                    .status(KmallStatusConstant.NORMAL)
                    .build();
            queryDTO.setPage(page);
            queryDTO.setSize(size);
            queryDTO.setOrderBy("sort asc");
            itemList = itemService.queryItemList(queryDTO);
        }
        result.put("list", itemList);
        result.put("page", page);
        result.put("size", size);
        return KmallResult.success(result);
    }

    /**
     * 商品搜索统计
     * @return
     */
    @GetMapping(value = "/search/hot")
    public KmallResult itemSearchHotWord() {
        // 热门搜索
        Set<String> hotSet = redisTemplate.opsForZSet().range(RedisKeyConstants.HOT_WORD, 0, -1);
        return KmallResult.success(hotSet);
    }

}
